package org.iteasy.framework.commons;

import com.iteasy.manage.exception.BizException;
import lombok.Data;

import java.io.Serializable;

/**
 * @author bo.chen
 */
@Data
public class Result<T> implements Serializable {

    private String code;

    private String message;

    private T content;

    private Result(String code,String message,T content) {
        this.code = code;
        this.message = message;
        this.content = content;
    }

    private Result(ResultEnum resultEnum,T content) {
        this.code = resultEnum.code;
        this.message = resultEnum.message;
        this.content = content;
    }

    private Result(ResultEnum resultEnum) {
        this.code = resultEnum.code;
        this.message = resultEnum.message;
    }

    public T unwrapAndThrowException() {
        if (ResultEnum.isSuccess(this.code)) {
            return this.content;
        }
        throw BizException.build(this.code,this.message);
    }

    public T unwrap() {
        if (ResultEnum.isSuccess(this.code)) {
            return this.content;
        }
        return null;
    }

    public boolean isSuccess() {
        return ResultEnum.isSuccess(this.code);
    }

    public static <T> Result<T> build(String code,String message,T content) {
        return new Result<>(code,message,content);
    }

    public static <T> Result<T> build(ResultEnum resultEnum,T content) {
        return new Result<>(resultEnum,content);
    }

    public static <T> Result<T> build(String code,String message) {
        return new Result<>(code,message,null);
    }

    public static <T> Result<T>  success(T content) {
        return new Result<>(ResultEnum.success,content);
    }

    public static <T> Result<T>  success() {
        return new Result<>(ResultEnum.success);
    }

    public static <T> Result<T> fail() {
        return new Result<>(ResultEnum.fail);
    }

}
